package com.instwall.callbase.thread;


import com.instwall.callbase.MConfig;
import com.instwall.callbase.tool.LogUtil;

public class Looper {
    private boolean isRunning = true;
    private WorkQueue workQueue;

    public Looper(WorkQueue workQueue) {
        if (workQueue != null) {
            this.workQueue = workQueue;
        } else {
            this.workQueue = new WorkQueue();
        }
    }

    private void looping() {
        while (isRunning) {
            ITask task;
            synchronized (this) {
                task = workQueue.getTask();
                if (task == null) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        LogUtil.LogI(MConfig.TAG,
                                "[Looper][looping]InterruptedException");
                        if (!isRunning) {
                            break;
                        }
                    }
                    continue;
                }
            }
            if (!isRunning) {
                break;
            }
            task.doWork();
        }
    }

    public void start() {
        isRunning = true;
        looping();
    }

    public void stop() {
        LogUtil.LogI(MConfig.TAG, "[Looper][stop]");
        ITask task = workQueue.getCurrentTask();
        try {
            if (task != null) {
                task.cancel();
            }
        } catch (Exception ex) {
            LogUtil.LogE(MConfig.TAG, "[Looper][stop] Exception : " + ex.getMessage());
        }
        isRunning = false;
        synchronized (this) {
            Thread.currentThread().interrupt();
        }
    }

    public void removeAll() {
        workQueue.removeAll();
    }


    public boolean getIsRunning() {
        return isRunning;
    }
}
